package cn.star.jots.employee.service.impl;

import cn.star.jots.base.exception.ServiceException;
import cn.star.jots.base.response.StatusCode;
import cn.star.jots.employee.mapper.EmployeeMapper;
import cn.star.jots.employee.pojo.dto.EmployeeLoginParam;
import cn.star.jots.employee.pojo.dto.EmployeeQuery;
import cn.star.jots.employee.pojo.dto.EmployeeSaveParam;
import cn.star.jots.employee.pojo.dto.EmployeeSavePassword;
import cn.star.jots.employee.pojo.entity.Employee;
import cn.star.jots.employee.pojo.vo.EmployeeVO;
import cn.star.jots.employee.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public EmployeeVO login(EmployeeLoginParam employeeLoginParam) {
        log.debug("用户登录业务,参数:{}", employeeLoginParam);
        EmployeeVO employeeVO = employeeMapper.selectByJobNumber(employeeLoginParam.getJobNumber());
        if (employeeVO == null) {
            log.warn("工号不存在:{}", employeeLoginParam.getJobNumber());
            throw new ServiceException(StatusCode.JOB_NUMBER_ERROR);
        }
        if (!employeeVO.getPassword().equals(employeeLoginParam.getPassword())) {
            log.warn("用户名或密码错误:{}", employeeLoginParam.getPassword());
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        log.debug("用户登录业务,结果:{}", employeeVO);
        return employeeVO;
    }

    @Override
    public EmployeeVO backup(EmployeeLoginParam employeeLoginParam) {
        log.debug("用户登录业务,参数:{}", employeeLoginParam);
        EmployeeVO employeeVO = employeeMapper.selectByPhone(employeeLoginParam.getPhone());
        if (employeeVO == null) {
            log.warn("工号不存在:{}", employeeLoginParam.getPhone());
            throw new ServiceException(StatusCode.PHONE_ERROR);
        }
        if (!employeeVO.getPassword().equals(employeeLoginParam.getPassword())) {
            log.warn("用户名或密码错误:{}", employeeLoginParam.getPassword());
            throw new ServiceException(StatusCode.PASSWORD_PHONE_ERROR);
        }
        log.debug("用户登录业务,结果:{}", employeeVO);
        return employeeVO;
    }

    @Override
    public List<EmployeeVO> selectAll(EmployeeQuery employeeQuery) {
        log.debug("查询员工信息业务,参数:{}", employeeQuery);
        return employeeMapper.selectAll(employeeQuery);
    }

    @Override
    public void saveInfo(EmployeeSaveParam employeeSaveParam) {
        log.debug("员工信息业务,参数:{}", employeeSaveParam);

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeSaveParam, employee);
        if (employee.getId() == null) {
            if (isPhoneExist(employeeSaveParam.getPhone())) {
                log.warn("手机号已存在:{}", employeeSaveParam.getPhone());
                throw new ServiceException(StatusCode.PHONE_EXIST);
            }
            employee.setPassword("123456");
            employee.setAvatar("/base/base.jpg");
            try {
                // 提取生日
                Date birthday = extractBirthDateFromIdNumber(employeeSaveParam.getIdNumber());
                employee.setBirthday(birthday);
                // 设置工号
                String jobNumber = generateJobNumber(employeeSaveParam.getIdNumber());
                employee.setJobNumber(jobNumber);
            } catch (ParseException | IllegalArgumentException e) {
                    log.error("处理身份证号时出错", e);
                    throw new ServiceException(StatusCode.IDNUMBER_EXIST);
                }
            employee.setCreateTime(new Date());
            employeeMapper.save(employee);
        } else { // 更新
            employee.setUpdateTime(new Date());
            employeeMapper.update(employee);
        }
        log.debug("员工信息业务,结果:{}", employee);
    }

    @Override
    public void updateStatus(Long id, String status) {
        log.debug("更新员工状态:id={},status={}", id, status);
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employee.setUpdateTime(new Date());
        employeeMapper.update(employee);
    }

    @Override
    public void updatePassword(Long id) {
        log.debug("更新员工密码:id={}", id);
        Employee employee = new Employee();
        employee.setId(id);
        employee.setPassword("123456");
        employee.setUpdateTime(new Date());
        employeeMapper.update(employee);
    }

    @Override
    public void delete(Long id) {
        log.debug("删除员工信息:id={}", id);
        employeeMapper.delete(id);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        log.debug("批量删除员工信息:ids={}", ids);
        for (Long id : ids){
            employeeMapper.delete(id);
        }
    }

    @Override
    public void savePassword(EmployeeSavePassword employeeSavePassword) {
        log.debug("修改密码:employeeSavePassword={}", employeeSavePassword);
        EmployeeVO employeeVO = employeeMapper.selectById(employeeSavePassword.getId());
        if (employeeVO.getPassword().equals(employeeSavePassword.getOldPassword())) {
          if (employeeVO.getPassword().equals(employeeSavePassword.getNewPassword())){
              throw new ServiceException(StatusCode.NEW_OLD_PASSWORD_ERROR);
          } else {
              Employee employee = new Employee();
              employee.setId(employeeSavePassword.getId());
              employee.setPassword(employeeSavePassword.getNewPassword());
              employee.setUpdateTime(new Date());
              employeeMapper.update(employee);
          }
        } else {
            log.warn("旧密码错误:{}", employeeSavePassword.getOldPassword());
            throw new ServiceException(StatusCode.OLD_PASSWORD_ERROR);
        }
    }

    // 判断手机号是否存在
    private boolean isPhoneExist(String phone) {
        EmployeeVO employeeVO = employeeMapper.selectByPhone(phone);
        return employeeVO != null;
    }

    // 定义一个专门用于解析出生日期的方法
    private Date extractBirthDateFromIdNumber(String idNumber) throws ParseException {
        if (idNumber == null || idNumber.length() != 18) {
            log.error("身份证号格式无效: {}", idNumber);
            throw new IllegalArgumentException("身份证号格式无效");
        }
        String birthDateStr = idNumber.substring(6, 14); // 提取出生日期部分
        // 使用线程安全的日期解析器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        log.debug("Birth Date String: {}", formatter);
        LocalDate localDate = LocalDate.parse(birthDateStr, formatter);
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
    private String generateJobNumber(String idNumber) {
        if (idNumber == null || idNumber.length() != 18) {
            throw new IllegalArgumentException("Invalid ID number format.");
        }
        // 获取当前日期并格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentDateStr = LocalDate.now().format(formatter);
        // 提取身份证号的后四位
        String idSuffix = idNumber.substring(14, 18);
        // 组合当前日期与身份证号后四位作为初始工号

        // 检查数据库中是否已经存在相同的工号（此步取决于你的业务需求）
        // 如果存在相同工号，则可以附加一个递增序列或随机数以确保唯一性

        return currentDateStr + idSuffix;
    }


}
